package com.pet_clinic.controller;


import com.atguigu.campus.pojo.Clazz;
import com.atguigu.campus.service.ClazzService;
import com.atguigu.campus.utils.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerMapping;

import java.util.List;

@RestController
@RequestMapping("/sms/clazzController")
public class clazzController {

    @Resource
    private ClazzService clazzService;
    @Autowired
    private HandlerMapping resourceHandlerMapping;

    /**
     * 带条件的分页查询功能
     * @param pn 当前页码
     * @param pageSize 每页显示的记录数
     * @param clazz 模糊查询条件
     * @return 返回查询结果封装page对象
     */
    @GetMapping("/getClazzsByOpr/{pn}/{pageSize}")
    public Result<Object> getClazzs(@PathVariable("pn")Integer pn, @PathVariable("pageSize")Integer pageSize,Clazz clazz){

        String gradeName=clazz.getGradeName();
        String name=clazz.getName();
        LambdaQueryWrapper<Clazz> lambdaQueryWrapper= new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StrUtil.isNotBlank(gradeName),Clazz::getGradeName,gradeName).like(StrUtil.isNotBlank(name),Clazz::getName,name).orderByDesc(Clazz::getId);
        Page<Clazz> page = clazzService.page(new Page<>(pn, pageSize), lambdaQueryWrapper);

        return Result.ok(page);
    }


    /**
     *单条记录和批量删除功能
     * @param idlist 请求体中待删除的年纪id的集合（List）
     * @return
     */
    @DeleteMapping("/deleteClazz")
    public Result<Object> deleteClazzs(@RequestBody List<Integer> idlist){

        //单条记录删除
        if(idlist.size()==1){
            clazzService.removeById(idlist.get(0));
        }else {
            clazzService.removeByIds(idlist);
        }
        return Result.ok();
    }

    /**
     * 根据判断请求体中是否存在id 进行判断是添加还是修改
     * @param clazz 把请求体中的JSON数据封装到实体类Clazz中
     * @return 返回成功
     */
    @PostMapping("/saveOrUpdateClazz")
    public Result<Object> saveOrUpdateClazz(@RequestBody Clazz clazz){

        //判断请求体中是否存在id，存在是修改，否则是添加
        Integer id = clazz.getId();
        if(id!=null){
            clazzService.update(clazz,new LambdaQueryWrapper<Clazz>().eq(Clazz::getId,id));
        }else {
            clazzService.save(clazz);
        }
        return Result.ok();
    }

    @GetMapping("/getClazzs")
    public Result getClazzs(){
        List<Clazz> list = clazzService.list();
        return Result.ok(list);
    }


}
